package com.github.alenfive;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.github.alenfive.wrapper.BodyReaderHttpServletRequestWrapper;
import org.jboss.logging.MDC;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class GlobalFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        MDC.put("traceId", Math.abs(String.valueOf(IdUtil.getSnowflake().nextId()).hashCode()));
        String contentType = request.getContentType()!=null? request.getContentType().toLowerCase():"";
        if (request.getContentLength()>0 && contentType.contains("json")) {
            //包装HttpServletRequest对象，缓存body数据，再次读取的时候将缓存的值写出,解决HttpServetRequest读取body只能一次的问题
            BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            byte[] bytes = requestWrapper.getRequestBodyByte();
            String jsonStr = new String(bytes, 0, bytes.length);
            requestWrapper.setAttribute("requestBodyData", JSON.parse(jsonStr));
            request = requestWrapper;
        }
        request.setAttribute("requestUrlParams", ServletUtils.queryAllUrlParams(request));
        request.setAttribute("requestHeaderParams", ServletUtils.queryAllHeaders(request));
        AnalysisUtils.printRequestDataParams(request);
        filterChain.doFilter(request, response);
    }

}
